/*
 * $Log: EmailManagerImpl.java,v $
 * Revision 1.10  2009/03/12 17:02:24  bgearring
 * changed for email server changes
 *
 * Revision 1.9  2009/03/10 16:35:06  bgearring
 * changed email info to props
 *
 * Revision 1.8  2008/11/26 17:20:18  bgearring
 * added logger
 *
 * Revision 1.7  2008/11/26 00:15:34  bgearring
 * fixed bug 671 (defaulting email if not found in db)
 *
 * Revision 1.6  2008/10/28 18:31:39  bgearring
 * changed to allow email sent to multiple addresses
 *
 * Revision 1.5  2008/10/13 22:45:12  bgearring
 * fixed email issue, factored rules to site visit mgr impl
 *
 * Revision 1.4  2008/10/13 19:17:34  pchapman
 * email work
 *
 * Revision 1.3  2008/10/09 19:43:02  bgearring
 * working on email impl
 *
 * Revision 1.2  2008/10/02 22:33:02  bgearring
 * working on email implementation
 *
 */
package com.redside.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.redside.Constants;
import com.redside.dao.EmailDao;
import com.redside.model.Email;
import com.redside.service.EmailManager;

/**
 * @author PCHAPMAN
 *
 */
public class EmailManagerImpl implements EmailManager {

	private final Log logger = LogFactory.getLog(getClass());
	private EmailDao emailDao;

	public void setEmailDao(EmailDao emailDao) {
		this.emailDao = emailDao;
	}

	/* (non-Javadoc)
     * @see gov.oregon.wems.manager.correspondence.email.EmailManager#delete(gov.oregon.wems.model.correspondence.email.Email)
     */
    public void delete(Email email) {
        emailDao.delete(email);
    }

    /* (non-Javadoc)
     * @see gov.oregon.wems.manager.correspondence.email.EmailManager#findAll()
     */
    public List<Email> findAll() {
        return emailDao.findAll();
    }

    /* (non-Javadoc)
     * @see gov.oregon.wems.manager.correspondence.email.EmailManager#findAllByType(java.lang.Long)
     */
    public List<Email> findAllByType(Long id) {
        return emailDao.findAllByType(id);
    }

    /* (non-Javadoc)
     * @see gov.oregon.wems.manager.correspondence.email.EmailManager#findById(java.lang.Long)
     */
    public Email findById(Long id) {
        return emailDao.findById(id);
    }

    /* (non-Javadoc)
     * @see gov.oregon.wems.manager.correspondence.email.EmailManager#save(gov.oregon.wems.model.correspondence.email.Email)
     */
    public Email save(Email email) {
        return emailDao.save(email);
    }


    /**
     * Sends basic email for WEMS 
     * application through the State mail server Lion
     * 
     * @return sent
     */
    public boolean sendMail(Long emailID, String countyId) throws Exception {
    	boolean success = false;

        // setup
    	String text = "";
        Properties props = System.getProperties();
        //props.put(ApplicationProperties.getProperty("mail_smtp_host"), ApplicationProperties.getProperty("mail_server"));
        MimeMessage message = new MimeMessage(Session.getDefaultInstance(props, null));

        if(null != emailID){
        	// New Complaint
        	if(emailID == 1){
        		text = Constants.NEW_COMPLAINT_TEXT;
        	}

        	// Reassigned Complaint
        	if(emailID == 2){
        		text = Constants.REASSIGNED_COMPLAINT_TEXT;
        	}

        	// Citation
        	if(emailID == 3){
        		text = Constants.CITATION_TEXT;
        	}
        }

        try {
        	logger.debug("trying sendMail");
        	Transport.send(setUpEmail(message, text, new ArrayList<Email>(emailDao.findByIdAndCountyId(emailID, countyId)), countyId));
        	success = true;
        	logger.debug("sendMail success");
        }
        catch(Exception e){
        	logger.debug("sendMail exception " + e);
        }

    	return success;
    }


    /**
     * Sets up the email message
     * 
     * @return
     */
    private Message setUpEmail(Message message, String text, List<Email> emailList, String countyId) throws Exception {
    	if (emailList.size() > 0) {
        	for(Email email:emailList){
        		logger.debug("\n\n sending email to: " + email.getEmailTo() + " for county " + countyId + "\n\n");

        		message.setFrom(new InternetAddress(email.getEmailFrom()));
        		message.setSubject(email.getSubject());
        		message.addRecipient(Message.RecipientType.TO, new InternetAddress(email.getEmailTo()));

        		if(!StringUtils.isEmpty(email.getEmailCc())){
        			message.addRecipient(Message.RecipientType.CC, new InternetAddress(email.getEmailCc()));
        		}
        	}
    	}
		else {
			// email to not found, set default
            message.setFrom(new InternetAddress(Constants.DEFAULT_EMAIL));
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(Constants.DEFAULT_EMAIL));
            message.setSubject(Constants.DEFAULT_SUBJECT + countyId);
		}

    	message.setContent(text, Constants.TEXT_HTML);

    	return message;
    }

}